package org.example.mybatis;

import org.example.mybatis.entity.User;
import org.example.mybatis.mapper.UserMapper;
import org.example.mybatis.session.SqlSession;
import org.example.mybatis.session.SqlSessionFactory;
import org.example.mybatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 应用入口类
 */
public class MybatisApplication {
    private static final Logger logger = LoggerFactory.getLogger(MybatisApplication.class);

    public static void main(String[] args) {
        // 构建SqlSessionFactory
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build("mybatis-config.xml");

        try (SqlSession sqlSession = factory.openSession()) {
            // 获取Mapper接口
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

            // 测试查询所有用户
            logger.info("====== 测试查询所有用户 ======");
            List<User> users = userMapper.selectAll();
            for (User user : users) {
                logger.info(user.toString());
            }

            // 测试根据ID查询用户
            logger.info("====== 测试根据ID查询用户 ======");
            User user = userMapper.selectById(1L);
            logger.info(user.toString());

            // 测试插入用户
            logger.info("====== 测试插入用户 ======");
            User newUser = new User("赵六", "123456", 23);
            int insertResult = userMapper.insert(newUser);
            logger.info("插入结果: {}", insertResult);

            // 再次查询所有用户
            logger.info("====== 再次查询所有用户 ======");
            users = userMapper.selectAll();
            for (User u : users) {
                logger.info(u.toString());
            }

            // 测试更新用户
            logger.info("====== 测试更新用户 ======");
            user.setUsername("张三修改");
            user.setAge(25);
            int updateResult = userMapper.update(user);
            logger.info("更新结果: {}", updateResult);

            // 测试删除用户
            logger.info("====== 测试删除用户 ======");
            int deleteResult = userMapper.deleteById(2L);
            logger.info("删除结果: {}", deleteResult);

            // 最后查询所有用户
            logger.info("====== 最后查询所有用户 ======");
            users = userMapper.selectAll();
            for (User u : users) {
                logger.info(u.toString());
            }
        }
    }
}